<template>
	<view class="bankcard-box">
		<view class="bankcard-top-box">
			<text>持卡人</text>
			<text class="bankcard-top-text-value">{{formStore.userRealName}}</text>
		</view>
		<view class="bankcard-title-box">请绑定商户本人的储蓄卡</view>
		<!-- 许可证照片 -->
		<view class="bankcard-image-box">
			<image class="bankcard-image" :src="formStore.bankFrontPhoto || '/static/bank_img.png'" mode="scaleToFill" @tap="showSelectImage"></image>
		</view>
		<view class="bankcard-title-box">请核对自动识别信息，若有误请更正</view>
		<!-- 银行卡表单信息 -->
		<view class="bankcard-form">
			<xh-form-input title="银行卡号" placeholder="请输入银行卡号" v-model="formStore.bankCardNo" @onBlur="editEnd"></xh-form-input>
			<xh-form-input title="开户银行" placeholder="通过银行卡号自动识别开户银行" isSelect v-model="formStore.branchBankName" :showRightIcon="false"></xh-form-input>
			<xh-form-input title="开户城市" placeholder="省/市" isSelect v-model="selectCityValue" @showSelect="showSelectCity"></xh-form-input>
			<xh-form-input title="开户支行" placeholder="请选择" isSelect v-model="formStore.bankName" @showSelect="showSelectSubBank"></xh-form-input>
			<xh-form-input title="手机号" :maxCount="11" placeholder="请输入银行预留手机号" v-model="formStore.bankPhone"></xh-form-input>
		</view>
		<!-- 底部提交按钮组件 -->
		<xh-submit :title="submitBtnTitle" @btnClick="submitClick"></xh-submit>
		<xh-select-city ref="selectCityRef"></xh-select-city>
	</view>
</template>

<script setup>
	import { computed, ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { useFormStore, useCityStore ,useUserStore} from '@/stores'
	import { getImageInfoByOcr, 
			 getCitysList, 
			 checkBankCardNo,
			  bindBankCard} from '@/config/api.js'

	const props = defineProps()
	//类型：type：add：添加结算卡
	const type = props.type || ''
	uni.setNavigationBarTitle({
		title:type == 'add' ? '绑定结算卡' : '结算卡信息'
	})
	const formStore = useFormStore()
	if(type == 'add'){
		formStore.$reset()
	}
	//提交按钮文字
	const submitBtnTitle = computed(()=>{
		if(type == 'add'){
			formStore.$reset()
			return '确认绑定'
		}
		else{
			if(formStore.merType == '1'){
				return '下一步'
			}
			else{
				return '提交'
			}
		}
	})
	//城市数据仓库
	const cityStore = useCityStore()
	const userStore = useUserStore()
	//城市选择组件ref对象
	const selectCityRef = ref()

	const selectCityValue = computed(() => {
		if (!uni.$u.test.isEmpty(formStore.provinceName)) {
			return `${formStore.provinceName},${formStore.cityName}`
		}
		return ''
	})
	onLoad(() => {
		getCitysListData()
	})
	//选择开户城市
	const showSelectCity = () => {
		selectCityRef.value.open()
	}
	//选择开户支行
	const showSelectSubBank = () => {
		if (uni.$u.test.isEmpty(formStore.branchBankName)) {
			uni.$tools.showToast('请选择开户银行')
			return
		} else if (uni.$u.test.isEmpty(formStore.provinceCode)) {
			uni.$tools.showToast('请选择开户城市')
			return
		}
		uni.navigateTo({
			url: '/pages/auth/select-sub-branch/select-sub-branch'
		})
	}
	/* 选择银行卡照片*/
	const showSelectImage = async () => {
		try {
			const res = await uni.$tools.uploadImage()
			formStore.bankFrontPhoto = res
			getOcrInfo(res)
		} catch (e) {
			uni.$tools.showToast(e)
		}
	}
	// 获取ocr识别信息
	const getOcrInfo = async (url) => {
		const res = await getImageInfoByOcr({ 'fileUrl': url, 'apiType': '02' })
		const ocrInfo = JSON.parse(res.result.data)
		const ocrRes = ocrInfo.result
		if (uni.$u.test.isEmpty(ocrRes)) {
			return
		}
		formStore.bankCardNo = uni.$tools.clearSpace(ocrRes.bank_card_number)
		if (uni.$u.test.isEmpty(formStore.bankCardNo)) {
			return
		}
		checkBankCardNoAction()
	}
	//获取城市数据
	const getCitysListData = async () => {
		if(uni.$u.test.isEmpty(cityStore.cityList)){
			const res = await getCitysList()
			cityStore.cityList = res.result
		}
	}
	///提交
	const submitClick = () => {

		if (uni.$u.test.isEmpty(formStore.bankFrontPhoto)) {
			uni.$tools.showToast('请上传银行卡卡号面照片')
			return
		} else if (uni.$u.test.isEmpty(uni.$tools.clearSpace(formStore.bankCardNo))) {
			uni.$tools.showToast('请输入银行卡号')
			return
		} else if (uni.$u.test.isEmpty(formStore.branchBankName)) {
			uni.$tools.showToast('未获取到开户银行')
			return
		} else if (uni.$u.test.isEmpty(formStore.provinceCode)) {
			uni.$tools.showToast('请选择开户城市')
			return
		} else if (uni.$u.test.isEmpty(formStore.bankName)) {
			uni.$tools.showToast('请选择开户支行')
			return
		} else if (uni.$u.test.isEmpty(formStore.bankPhone.trim())) {
			uni.$tools.showToast('请输入银行预留手机号')
			return
		} else {
			if(type == 'add'){
				addBankCardAction()
			}
			else{
				if(formStore.merType == '1'){
					//个人认证跳转到店铺信息
					uni.navigateTo({
						url: '/pages/auth/store-info/store-info'
					})
				}
				else{
					submitAction()
				}
				
			}
		}
	}
	//根据银行卡号获取银行信息
	const checkBankCardNoAction = () => {
		console.log('dasadadsa')
		checkBankCardNo({ cardNo: formStore.bankCardNo }).then(res => {
			if (uni.$u.test.isEmpty(res.result) || res.result.cardType != '01') {
				uni.$tools.showToast('请绑定借记卡')
				formStore.branchBankName = ''
				formStore.bankBranchNo = ''
				formStore.branchBankNo = ''
				formStore.bankName = ''
				formStore.bankNo = ''
				return
			} else {
				formStore.branchBankName = res.result.bankName
				formStore.bankBranchNo = res.result.bankNo
			}
		}).catch((err) => {
			if(!uni.$u.test.isEmpty(err)){
				formStore.branchBankName = ''
				formStore.bankBranchNo = ''
				formStore.branchBankNo = ''
				formStore.bankName = ''
				formStore.bankNo = ''
			}
		})
	}

	///输入框失去焦点时触发
	const editEnd = () => {
		console.log('编辑结束')
		if (uni.$u.test.isEmpty(uni.$tools.clearSpace(formStore.bankCardNo))) {
			return
		}
		checkBankCardNoAction()
	}
	//添加结算卡
	const addBankCardAction = ()=>{
		uni.$pop.show({
			type:'alert',
			config:{
				title:'温馨提示',
				desc:'确认要提交绑定吗？',
				buttons:['取消','确认']
			}
		},(value)=>{
			if(value == '确认'){
				submitAddBankCard()
			}
		})
	}
	//确认提交添加结算卡
	const submitAddBankCard = ()=>{
		let params = {}
		//结算卡信息
		params.cardPicUrl = formStore.bankFrontPhoto
		params.settleCardNo = uni.$tools.clearSpace(formStore.bankCardNo)
		params.settleType = '1'
		params.settleName = userStore.user.userName
		params.bankNo = formStore.bankNo
		params.bankName = formStore.bankName
		if(!uni.$u.test.isEmpty(formStore.bankBranchNo)){
			params.bankBranchNo = formStore.bankBranchNo
		}
		if(!uni.$u.test.isEmpty(formStore.branchBankName)){
			params.bankBranch = formStore.branchBankName
		}
		params.phoneNo = uni.$tools.clearSpace(formStore.bankPhone)
		let bankAddress = ''
		if(!uni.$u.test.isEmpty(formStore.provinceCode) && uni.$u.test.isEmpty(formStore.cityCode)){
			bankAddress = formStore.provinceCode
		}
		else if(!uni.$u.test.isEmpty(formStore.provinceCode) && !uni.$u.test.isEmpty(formStore.cityCode)){
			bankAddress = `${formStore.provinceCode},${formStore.cityCode}`
		}
		params.bankAddress = bankAddress
		bindBankCard().then(res=>{
			formStore.$reset()
			uni.$u.tools.showToast('绑定成功')
			uni.navigateBack()
		}).catch(err=>{
			
		})
	}
	//个体工商户认证
	const submitAction = ()=>{
		uni.$pop.show({
			type:'alert',
			config:{
				title:'温馨提示',
				desc:'确认要提交审核吗？',
				buttons:['取消','确认']
			}
		},(value)=>{
			if(value == '确认'){
				uni.$u.throttle(submitMerchantInfoAction, 500)
			}
		})
	}
	//确认提交个体工商户/企业商户信息审核
	const submitMerchantInfoAction = ()=> {
		let params = {}
		//法人身份信息
		params.userRealName = formStore.userRealName.trim()
		params.identityNo = formStore.identityNo.trim()
		let certValidTime = ''
		if(formStore.isLongTime){
			certValidTime = `${formStore.certStartTime},长期`
		}
		else{
			certValidTime = `${formStore.certStartTime},${formStore.certEndTime}`
		}
		params.certValidTime = certValidTime
		params.frontPhoto = formStore.frontPhoto
		params.reversePhoto = formStore.reversePhoto
		params.handsetPhoto = formStore.handsetPhoto
		if(!uni.$u.test.isEmpty(formStore.sex)){
			params.sex = formStore.sex
		}
		if(!uni.$u.test.isEmpty(formStore.nation)){
			params.nation = formStore.nation
		}
		params.address = uni.$tools.clearSpaceAndEnter(formStore.address)
		
		//结算卡信息
		params.settleType = '1'
		params.bankFrontPhoto = formStore.bankFrontPhoto
		params.bankCardNo = uni.$tools.clearSpace(formStore.bankCardNo)
		params.bankNo = formStore.bankNo
		params.bankName = formStore.bankName
		if(!uni.$u.test.isEmpty(formStore.bankBranchNo)){
			params.bankBranchNo = formStore.bankBranchNo
		}
		params.branchBankName = formStore.branchBankName
		params.bankPhone = uni.$tools.clearSpace(formStore.bankPhone)
		let bankAddress = ''
		if(!uni.$u.test.isEmpty(formStore.provinceCode) && uni.$u.test.isEmpty(formStore.cityCode)){
			bankAddress = formStore.provinceCode
		}
		else if(!uni.$u.test.isEmpty(formStore.provinceCode) && !uni.$u.test.isEmpty(formStore.cityCode)){
			bankAddress = `${formStore.provinceCode},${formStore.cityCode}`
		}
		params.bankAddress = bankAddress
		//店铺信息
		params.mercSn = formStore.mercSn.trim()
		params.mccType = formStore.mccType
		params.bussinessAddr = uni.$tools.clearSpaceAndEnter(formStore.bussinessAddr)
		if(!uni.$u.test.isEmpty(formStore.settleId)){
			params.settleId = formStore.settleId
		}
		params.merType = formStore.merType
		const bussinessArea = `${formStore.storeProvinceName},${formStore.storeCityName},${formStore.storeAreaName}`
		params.bussinessArea = bussinessArea
		
		///企业信息
		params.busLicenseInfo = form.busLicenseInfo
		params.busRegType = form.busRegType
		params.busLicenseId = form.busLicenseId
		params.doorPhoto = form.doorPhoto
		params.indoorPhoto = form.indoorPhoto
		params.cashierPhoto = form.cashierPhoto
		params.companyName = form.companyName
		if(formStore.busRegType == '1'){
			params.busRegStartDt = form.busRegStartDt
			params.busRegEndDt = form.busRegEndDt
		}
		else{
			params.busRegStartDt = form.busRegStartDt
			params.busRegEndDt = '2999-12-30'
		}
		//提交商户信息
		submitMerchantInfo(params).then(res=>{
			submitMerchantReportAction()
		}).catch(()=>{
		})
	}
	//提交商户报备
	const submitMerchantReportAction = ()=>{
		submitMerchantReport({"uptType":"4"}).then(res=>{
			showResultPage('submit')
		}).catch(err=>{
			if(!uni.$u.test.isEmpty(err.message)){
				userStore.user.authRemark = err.message.content
			}
			else{
				userStore.user.authRemark = '提交失败，请检查网络'
			}
			showResultPage('fail')
		})
	}
	//跳转结果页面
	const showResultPage = (type)=>{
		uni.switchTab({
			url:'/pages/my/my',
			complete() {
				formStore.$reset()
				uni.navigateTo({
					url:`/pages/result/result?type=${type}`
				})
			}
		})
	}
</script>

<style lang="scss" scoped>
	.bankcard-box {
		width: 100%;
		font-size: 28rpx;

		.bankcard-top-box {
			display: flex;
			align-items: center;
			padding: 30rpx;
			background-color: white;

			.bankcard-top-text-value {
				margin-left: 40rpx;
				color: $xh-subtitle-color;
			}
		}

		.bankcard-title-box {
			padding: 26rpx 30rpx;
			font-weight: bold;
			color: $xh-subtitle-color;
		}

		.bankcard-image-box {
			background-color: white;
			padding: 30rpx 60rpx;

			.bankcard-image {
				width: 630rpx;
				height: 270rpx;
			}
		}
	}
</style>